package ru.evga.gwt.lib.common.client.ui.editor;

import java.util.List;

import ru.evga.gwt.lib.common.client.domain.BaseEntityDto;
import ru.evga.gwt.lib.common.client.request.IServiceRequestCallback;
import ru.evga.gwt.lib.common.client.request.RequestFactory;
import ru.evga.gwt.lib.common.client.request.params.SaveEntityParams;
import ru.evga.gwt.lib.common.client.ui.editor.IEntityEditor;
import ru.evga.gwt.lib.common.client.ui.editor.ISaveEntityCallback;

import com.google.gwt.editor.client.EditorError;
import com.google.gwt.editor.client.SimpleBeanEditorDriver;


public class DtoEditManager<T extends BaseEntityDto, E extends IEntityEditor<T>>
    extends EditManager<T, E, E>
    implements EditManager.EditCallback<T>
{
    
    private E editor;
    private T savedEntity;
    private ISaveEntityCallback<T> saveEntityCallback;
    private String entityName;

    public void init(T data, E editor, ISaveEntityCallback<T> saveEntityCallback, SimpleBeanEditorDriver<T, E> driver, String entityName)
    {
        this.saveEntityCallback = saveEntityCallback;
        this.editor = editor;
        this.entityName = entityName; 
        super.init(data, editor, editor, this, driver);
    }

    public void onSave(T editedData)
    {
        saveEntity(editedData);
    }
    
    public void onCancel(T editedData) 
    {
        
    };

    public void onError(List<EditorError> errors)
    {
        //Shows errors in editor
        editor.showError(errors);
    }
    
    private void saveEntity(T entity)
    {
        SaveEntityParams<T> params = SaveEntityParams.createEmptyParams();
        params.setEntity(entity);
        params.setEntityName(entityName);
        RequestFactory.saveEntity(params, new IServiceRequestCallback<T, String>()
        {

            public void ok(T data)
            {
                savedEntity = data;
                saveEntityCallback.onEntitySaved(savedEntity);
            }

            public void error(String data)
            {
                editor.onServiceError(data);
            }
            
        });
    }
    
    public T getPersistedEntity()
    {
        return this.savedEntity;
    }
}
